layui.use(['form', 'table', 'layer', 'element'], function () {
    var form = layui.form,
        table = layui.table,
        layer = layui.layer,
        $ = layui.jquery,
        element = layui.element;
    loadUserTab();
    $(".layui-nav-item").bind("click", function (me) {
        if (me.target.innerHTML == "用户管理") {
            $("section").eq(0).removeClass("layui-hide");
            $("section").eq(1).addClass("layui-hide");
            loadUserTab();
        } else {
            $("section").eq(1).removeClass("layui-hide");
            $("section").eq(0).addClass("layui-hide");
            loadPostTab();
        }
    });

    form.on('switch(userStatus)', function (data) {
        let userId = data.value;
        let status = data.othis[0].innerText == "启用" ? 1 : 0;
        console.log(userId + " " + status);
        $.post('../user/userStatus', {"userId": userId, "userStatus": status}, function (ret) {
            if (ret.code == 0) {
                layer.msg(ret.msg);
            }
        });
    });

    function statusIns(data) {
        let postId = data.value;
        let statusText = data.othis[0].innerText;
        let status = statusText.startsWith("已") ? 1 : 0;
        switch (statusText.substring(1)) {
            case "审核":
                return {"postId":postId,"status": status};
                break;
            case "加精":
                return {"postId":postId,"isFine": status};
                break;
            case "置顶":
                return {"postId":postId,"isTop": status};
                break;
        }
    }

    form.on('switch(postStatus)', function (data) {
        $.post('../index/editPost', statusIns(data), function (ret) {
            if (ret.code == 0) {
                layer.msg(ret.msg);
            }
        });
    });

    function loadUserTab() {
        //表格实例化
        let userTab = table.render({
            elem: "#userTab",
            url: "../user/userPage",
            page: true,
            cols: [[ //表头
                {type: 'checkbox'},
                {field: 'id', title: 'ID', width: 60, align: 'center'},
                {field: 'nickName', title: '昵称', width: 100},
                {field: 'sex', title: '性别', width: 60, align: 'center'},
                {field: 'email', title: '邮箱', width: 80},
                {field: 'headImg', title: '头像', width: 80},
                {field: 'wealth', title: '财富', width: 80},
                {field: 'grade', title: 'VIP值', width: 80},
                {field: 'role', title: '角色', width: 60, align: 'center'},
                {
                    field: 'status', title: '账号状态', width: 120, align: 'center', templet: function (d) {
                        let isCkecked = d.userStatus == "1" ? "checked" : "";
                        return '<input type="checkbox" lay-filter="userStatus" value="' + d.id + '" lay-skin="switch" lay-text="启用|禁用" ' + isCkecked + '> ';
                    }
                },
                {field: 'emailStatus', title: '邮箱状态', width: 80},
                {field: 'createTime', title: '创建时间', width: 160},
                {field: 'updateTime', title: '更新时间', width: 160},
                {title: '操作', align: 'center', toolbar: '#barDemo', fixed: 'right', width: 150}
            ]]
        });

        table.on('tool(userTab)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
            if (layEvent === 'del') { //删除
                layer.confirm('真的删除行么', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url: "../management/userDel",
                        type: "post",
                        data: {
                            id: data.id
                        },
                        success: function (res) {
                            layer.msg("成功");
                        },
                        error: function (e) {
                            layer.msg("error");
                        }
                    });
                });
            } else if (layEvent === 'edit') { //编辑
                layer.open({
                    title: ['编辑用户', 'font-size:18px'],
                    type: 2,
                    area: ['30%', '70%'], //宽高
                    content: ['../page/editUserForm.html', 'no'], //弹出的页面
                    shadeClose: true, //点击遮罩关闭
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                        //初始化表单数据的值
                        body.find(".uId").val(data.id);
                        body.find(".nickName").val(data.nickName);
                        body.find(".tel").val(data.tel);
                        body.find(".email").val(data.email);
                        body.find(".city").val(data.city);
                        body.find(".signature").val(data.signature);
                        let sexIndex = data.sex == '男' ? 0 : 1;
                        console.log();
                        data.sex == '男' ? body.find("input[name=sex][value=男]").next().addClass("layui-form-radioed").children("i").html("&#xe643;") :
                            body.find("input[name=sex][value=女]").next().addClass("layui-form-radioed").children("i").html("&#xe643;");
                    }
                });
            } else if (layEvent === 'LAYTABLE_TIPS') {
                layer.alert('Hi，头部工具栏扩展的右侧图标。');
            }
        });
    }

    function loadPostTab() {
        let postTab = table.render({
            elem: "#postTab",
            url: "../management/postPage",
            page: true,
            cols: [[ //表头
                {type: 'checkbox'},
                {field: 'id', title: 'ID', width: 60, align: 'center'},
                {field: 'nickName', title: '发帖用户', width: 110},
                {field: 'columnName', title: '所在专栏', width: 110},
                {field: 'title', title: '标题', width: 120, align: 'center'},
                {field: 'kiss', title: '悬赏', width: 80},
                {
                    field: 'status', title: '状态', width: 100, templet: function (d) {
                        console.log(d);
                        let isCkecked = d.status == "1" ? "checked" : "";
                        return '<input type="checkbox" lay-filter="postStatus" value="' + d.id + '" lay-skin="switch" lay-text="已审核|未审核" ' + isCkecked + '> ';
                    }
                },
                {
                    field: 'isFine', title: '精贴', width: 100, templet: function (d) {
                        let isCkecked = d.isFine == "1" ? "checked" : "";
                        return '<input type="checkbox" lay-filter="postStatus" value="' + d.id + '" lay-skin="switch" lay-text="已加精|未加精" ' + isCkecked + '> ';
                    }
                },
                {
                    field: 'isTop', title: '置顶', width: 100, templet: function (d) {
                        let isCkecked = d.isTop == "1" ? "checked" : "";
                        return '<input type="checkbox" lay-filter="postStatus" value="' + d.id + '" lay-skin="switch" lay-text="已置顶|未置顶" ' + isCkecked + '> ';
                    }
                },
                {field: 'isClosed', title: '已结', width: 60, align: 'center'},
                {field: 'browseNum', title: '人气数', width: 75, align: 'center'},
                {field: 'replyNum', title: '回复数', width: 75},
                {field: 'createTime', title: '创建时间', width: 160},
                {title: '操作', align: 'center', toolbar: '#barDemo2', fixed: 'right', width: 150}
            ]]
        });

        table.on('tool(postTab)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
            if (layEvent === 'del') { //删除
                layer.confirm('真的删除行么', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                    $.ajax({
                        url: "../management/postDel",
                        type: "post",
                        data: {
                            id: data.id
                        },
                        success: function (res) {
                            layer.msg("成功");
                        },
                        error: function (e) {
                            layer.msg("error");
                        }
                    });
                });
            }
        });
    }

});